package utils

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"

	"tuiwen-go/internal/config"
)

// callGPTAPI 调用 GPT API 生成提示词
func CallGPTAPI(t, content string) (string, error) {
	// 从数据库获取 GPT 配置
	gptURL, ok := config.GetSetting("gpt_url")
	if !ok {
		log.Printf("获取 GPT URL 设置失败: gpt_url not found in cache")
		gptURL = "" // Fallback to empty string or default URL
	}

	gptAccessKey, ok := config.GetSetting("gpt_accesskey")
	if !ok {
		log.Printf("获取 GPT Access Key 设置失败: gpt_accesskey not found in cache")
		gptAccessKey = "" // Fallback to empty string
	}

	// 检查配置是否为空
	if gptURL == "" || gptAccessKey == "" {
		return "", fmt.Errorf("GPT 配置不完整：gpt_url 或 gpt_accesskey 为空")
	}
	gptPromptPrefix := ""
	switch t {
	case "role":
		gptPromptPrefix, ok = config.GetSetting("gpt_role_prefix")
		if !ok {
			log.Printf("获取 GPT Prompt Prefix 设置失败: gpt_role_prefix not found in cache")
			gptPromptPrefix = "" // Fallback to empty string
		}
	case "prompt":
		gptPromptPrefix, ok = config.GetSetting("gpt_prompt_prefix")
		if !ok {
			log.Printf("获取 GPT Prompt Prefix 设置失败: gpt_prompt_prefix not found in cache")
			gptPromptPrefix = "" // Fallback to empty string
		}
	case "split":
		gptPromptPrefix, ok = config.GetSetting("gpt_split_prefix")
		if !ok {
			log.Printf("获取 GPT Prompt Prefix 设置失败: gpt_split_prefix not found in cache")
			gptPromptPrefix = "" // Fallback to empty string
		}
	}
	gptModel, ok := config.GetSetting("gpt_model")
	if !ok {
		log.Printf("获取 GPT Model 设置失败: gpt_model not found in cache")
		gptModel = "gpt-3.5-turbo" // Fallback to default model
	}
	// 构建请求体
	reqBody := map[string]interface{}{
		"model":    gptModel,
		"messages": []map[string]string{{"role": "user", "content": gptPromptPrefix + content}},
	}

	jsonBody, err := json.Marshal(reqBody)
	if err != nil {
		return "", fmt.Errorf("编码请求体失败: %w", err)
	}

	// 创建 HTTP 客户端
	client := &http.Client{Timeout: 30 * time.Second}

	// 构建请求
	req, err := http.NewRequest("POST", gptURL, bytes.NewBuffer(jsonBody))
	if err != nil {
		return "", fmt.Errorf("创建请求失败: %w", err)
	}
	log.Printf("gpt请求参数: %s", string(jsonBody))

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+gptAccessKey)

	// 发送请求
	res, err := client.Do(req)
	if err != nil {
		return "", fmt.Errorf("发送请求失败: %w", err)
	}
	defer res.Body.Close()

	// 读取响应
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return "", fmt.Errorf("读取响应失败: %w", err)
	}

	// 解析响应
	var gptResponse struct {
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			}
		}
	}

	if err := json.Unmarshal(body, &gptResponse); err != nil {
		return "", fmt.Errorf("解析响应失败: %w", err)
	}

	if len(gptResponse.Choices) > 0 {
		return gptResponse.Choices[0].Message.Content, nil
	}

	return "", fmt.Errorf("未从 GPT API 获取到内容")
}
